import { defineStore } from 'pinia'
import api from '@/api/index'

let loginInterval = null
export const useUserStore = defineStore('user', {
  state: () => {
    let user = {
      operateId: 0,
      operateName: '',
      companyId: 0,
      companyName: '',
      departId: 0,
      departName: '',
      platform: ''
    }
    return {
      user,
      token: ''
    }
  },
  actions: {
    async login() {
      const settings = JSON.parse(localStorage.settings)
      const res = await api.login({
        account: settings.account.account,
        password: settings.account.password,
        platform: 'ytj'
      })
      this.user = res.data.user
      this.token = res.data.token
      localStorage.user = JSON.stringify(res.data.user)
      localStorage.token = res.data.token
      localStorage.loginExpired = +new Date()
      if (loginInterval === null) {
        loginInterval = setInterval(this.login, 6 * 60 * 60 * 1000)
      }
    },
    logout() {
      this.token = ''
      for (const key in this.user) {
        this.user[key] = ''
      }
      localStorage.clear()
    }
  }
})
